package com.example.config;

import com.example.resp.ResultVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class ControllerHandleAdvice implements ResponseBodyAdvice<Object> {
    // ResponseBodyAdvice 是对 Controller 返回的内容在 HttpMessageConverter
    // 进行类型转换之前拦截，进行相应的处理操作后，再将结果返回给客户端。

    @Override
    // 判断是否要交给 beforeBodyWrite 方法执行，ture：需要；false：不需要
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // response 是ResultVo类型，或者注释了NotControllerResponseAdvice都不进行包装
        return !(methodParameter.getParameterType().isAssignableFrom(ResultVo.class)
                || methodParameter.hasMethodAnnotation(NoWrapResponseAdvice.class));
    }

    @Override
    // 对 response 进行具体的处理
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 如果body已经被包装了，就不进行包装
        if (body instanceof ResultVo) {
            return body;
        }
        // String类型不能直接包装 否则会抛出 ClassCastException
        if (body instanceof String) {
            try {
                // 如果返回值是String类型，那就手动把Result对象转换成JSON字符串
                return new ObjectMapper().writeValueAsString(ResultVo.success(body));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        // 否则直接包装成ResultVo返回
        return ResultVo.success(body);
    }

}